<%@ page language="JAVA" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <%
        String bathPath = request.getContextPath();
        pageContext.setAttribute("bathPath", bathPath);
    %>
    <meta charset="UTF-8">
    <title>班次管理</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="stylesheet" href="${bathPath}/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="${bathPath}/css/formSelects-v4.css">
    <link rel="stylesheet" href="${bathPath}/css/common.css">
    <link rel="stylesheet" href="${bathPath}/css/timeSlot.css">
    <style>
        #addMask,#addTimeMask{
            display: none;
        }
        .addTimeSlot .layui-form-label {
            width: 169px;
        }
        .addTimeSlot .layui-form-item .layui-input-inline{
            width:212px;
        }
        .demo-class{
            overflow-y: auto;
        }

        .demo-class .layui-layer-content{
            overflow-x: hidden !important;
        }
        @media all and (max-width:1024px){
            .demo-class .layui-layer-content{
                overflow-x: auto !important;
            }
        }

        .layui-layer-title{
            position:relative;
        }

        .time-mid{
            position: absolute;
            left: 0;
            top: 10px;
            right: 0;
            margin: auto;
            width: 100px;
        }
    </style>
</head>
<body>

<div class="layui-btn-group ml-54 demoTable radius">
    <button class="layui-btn layui-btn-normal" data-type="add">新增</button>
</div>


<table class="layui-hide" id="timeSlotTable" lay-filter="test"></table>

<div id="chart-wrapper" style="display: none;">

    <div class="chartContent" id="chartContent" style="width:900px;height:540px;max-width:100%;margin:0 auto;overflow-x:hidden;overflow-y: auto;"></div>
</div>


<!--添加弹出层-->
<div id="addMask">
    <form class="layui-form time-slot" action="#" id=runForm" lay-filter="example">
        <input type="hidden" id="id" name="id">
        <div class="layui-form-item">
            <label class="layui-form-label">班次名称</label>
            <div class="layui-input-inline">
                <input type="text" class="layui-input" name="name" id="name" lay-verify="required"
                       placeholder="请输入班次名称">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">启用日期</label>
            <div class="layui-input-inline">
                <input type="text" name="startTime" class="layui-input" id="startTime" lay-verify="required"
                       placeholder="请选择时间">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">周期数</label>
            <div class="layui-input-inline">
                <input type="text" name="cycle" class="layui-input" id="cycle" lay-verify="required|number"
                       placeholder="请输入周期数">
            </div>
        </div>


        <div class="layui-form-item">
            <label class="layui-form-label">周期单位</label>
            <div class="layui-input-inline">
                <select name="units" id="units" lay-verify="required">
                    <option value=""></option>
                    <option value="1">周</option>
                    <option value="2">天</option>
                    <option value="3">月</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button lay-submit class="layui-btn layui-btn-normal" lay-filter="formTest"  id="confirm">确定</button>
                <button type="button" class="layui-btn layui-btn-primary cancel-layer">取消</button>
            </div>
        </div>
    </form>
</div>

<!--增加时段弹出层-->
<div id="addTimeMask">
    <form class="layui-form time-slot addTimeSlot" action="#" lay-filter="example2">
        <input type="hidden" id="numRunId">
        <input type="hidden" id="sTime">
        <input type="hidden" id="sUnits">
        <input type="hidden" id="sCycle">
        <div class="layui-form-item">
            <label class="layui-form-label">选择所属班次时段</label>
            <div class="layui-input-inline">
                <select name="classTimeSlot" id="classTimeSlot" lay-verify="required">

                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">选择要添加该时间段的日期</label>
            <div class="layui-input-inline">
                <select name="dateTimeSlot" xm-select="selectId" xm-select-show-count="5" xm-select-direction="down" name="dateTimeSlot" id="dateTimeSlot" lay-verify="required"></select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">该时段是否记为加班</label>
            <div class="layui-input-inline">
                <input type="radio" name="isAddWork" value="0" title="否" lay-filter="isAddWork">
                <input type="radio" name="isAddWork" value="1" title="是" lay-filter="isAddWork" checked>
            </div>
        </div>

        <div class="layui-form-item" id="addWorkTimeWrap">
            <label class="layui-form-label">记加班分钟数</label>
            <div class="layui-input-inline">
                <input type="text" name="addWorkTime" class="layui-input" id="addWorkTime" lay-verify="required|number" placeholder="请输入分钟数">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button lay-submit class="layui-btn layui-btn-normal" lay-filter="formTest2">确定</button>
                <button type="button" class="layui-btn layui-btn-primary cancel-layer">取消</button>
            </div>
        </div>

    </form>
</div>
<script type="text/html" id="barDemo">
<%--    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="add">新增</a>--%>
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="addTime">增加时段</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delTime">清除时段</a>
</script>
<script src="${bathPath}/layui/layui.js" charset="utf-8"></script>
<script type="text/javascript" src="${bathPath}/js/jquery-1.9.1.min.js"></script>
<script src="${bathPath}/js/formSelects-v4.min.js"></script>
<script type="text/javascript" src="${bathPath}/js/common.js"></script>
<script src="${bathPath}/js/echarts.js" type="text/javascript"></script>
<script>
    var echartsHeight = '';
    var layerIndex = null;
    var myChart = null;
    $(function () {
        initLayUI();
        // auto_height();
        // onresize=auto_height;
     })

    function auto_height(){
       document.getElementById("chartContent").style.height = document.documentElement.clientHeight-210+"px";
       echartsHeight = document.documentElement.clientHeight-260+"px";
    }

    function initLayUI() {
        layui.use(['form', 'laydate', 'layer', 'table'], function () {
            var form = layui.form;
            var laydate = layui.laydate;
            var table = layui.table;
            var layer = layui.layer;
            var formSelects = layui.formSelects;


            var $ = layui.$, active = {
                reload: function () {
                    //执行重载
                    table.reload('testReload', {
                        where: {
                        }
                    });
                }
            };

            $('.radius .layui-btn').on('click', function () {
                runEvent();
            });

            table.render({
                elem: '#timeSlotTable'
                , url: '${bathPath}/numRun/selectAll.action'
                , toolbar: true
                ,height: 'full-38'
                , title: '班次管理表'
                , cols: [[
                    {field: 'name', title: '名称'}
                    , {field: 'startTime', title: '启用日期'}
                    , {field: 'cycle', title: '周期数'}
                    , {
                        field: 'units', title: '周期单位', templet: function (data) {
                            return formatterCycleType(data.units);
                        }
                    }
                    , {toolbar: '#barDemo', title: '操作', width: 310}
                ]]
                , page: false
                , response: {
                    statusCode: 0 //重新规定成功的状态码为 200，table 组件默认为 0
                }
                , id: 'testReload'
                ,parseData: function(res){ //res 即为原始返回的数据
                    $.each(res.data,function(i,item){
                        var time = formatTime(item.startTime);
                        res.data[i].startTime= time.split(' ')[0];
                    })
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": res.count, //解析数据长度
                        "data": res.data//解析数据列表
                    };
                }
            });

            //点击添加班次时段中的是否加班单选按钮
            form.on('radio(isAddWork)', function(data){
                if(data.value == 1){
                    $("#addWorkTimeWrap").show();
                    $("#addWorkTime").attr("lay-verify","required|number");
                }else{
                    $("#addWorkTimeWrap").hide();
                    $("#addWorkTime").removeAttr("lay-verify");

                }
            });

            //监听工具条
            table.on('tool(test)', function (obj) {
                var data = obj.data;
                if (obj.event === 'add') {
                    //传入add逻辑事件
                    localStorage.setItem('delTime','');
                    runEvent();
                } else if (obj.event === 'del') {
                    localStorage.setItem('delTime','');
                    layer.confirm('真的删除该班次吗?', function (index) {
                        var dataJson = {};
                        dataJson.id = data.id;
                        $.ajax({
                            type: 'POST',
                            data: {numRunId:data.id},
                            contentType:"application/x-www-form-urlencoded",
                            url: '${bathPath}/userOfRunDeil/selectUserOfRunDeilInfo.action',
                            success: function (res) {
                                if(res.length === 0){
                                    $.ajax({
                                        type: 'POST',
                                        data: dataJson,
                                        contentType:"application/x-www-form-urlencoded",
                                        url: '${bathPath}/numRun/delete.action',
                                        success: function (data) {
                                            if (data == 'SUCCESS') {
                                                layer.alert('班次已删除!',{
                                                    icon:1,
                                                    title:'提示'
                                                })
                                                layer.close(index);
                                                active.reload();
                                            }
                                        }
                                    })
                                }else{
                                    layer.alert('该班次正在使用中,无法删除!',{
                                        icon:2,
                                        title:'提示'
                                    })
                                }
                            }
                        })
                    });
                }else if(obj.event === 'addTime'){
                    localStorage.setItem('delTime','');
                    runAddTimeEvent(data);
                } else if (obj.event === 'edit') {
                    localStorage.setItem('delTime','');
                    //传入编辑逻辑事件
                    runEvent(data);
                } else if (obj.event === 'cancel') {
                    localStorage.setItem('delTime','');
                    layer.close(layerIndex);
                }else if(obj.event === 'delTime'){
                    localStorage.setItem('delTime',0);
                    $.ajax({
                        type: 'POST',
                        data: {
                            numRunId:data.id,
                            deilType:1
                        },
                        contentType:"application/x-www-form-urlencoded",
                        url: '${bathPath}/numRunDeil/selectAll.action',
                        success: function (res) {
                            let result = res.data;
                            if(result && result.length > 0){
                                layer.confirm('真的清除时段吗',{
                                    cancel: function(index, layero){
                                        //取消操作，点击右上角的X
                                        localStorage.setItem('delTime', '');
                                    }
                                }, function (index) {
                                    //清除时段逻辑
                                    var dataJson = {};
                                    dataJson.numRunId = data.id;
                                    $.ajax({
                                        type: 'POST',
                                        data: dataJson,
                                        contentType:"application/x-www-form-urlencoded",
                                        url: '${bathPath}/numRunDeil/delete.action',
                                        success: function (data) {
                                            layer.close(index);
                                            if (data == 'SUCCESS') {
                                                layer.alert('删除成功!',{
                                                    icon:1,
                                                    title:'提示'
                                                })
                                                active.reload();
                                            }else{
                                                layer.alert('删除失败!',{
                                                    icon:2,
                                                    title:'提示'
                                                })
                                            }
                                            localStorage.setItem('delTime','');
                                        }
                                    })
                                },
                                function(){
                                    localStorage.setItem('delTime', '');
                                })
                            }else{
                                layer.alert('暂未添加时间段!',{
                                    icon:5,
                                    title:'提示'
                                })
                                localStorage.setItem('delTime','');
                            }
                        }
                    })
                }
            });




            //监听行单击事件
            table.on('row(test)', function(obj){
                localStorage.setItem('timeDelete','');
                localStorage.setItem('objData',JSON.stringify(obj.data));
                //避免新增编辑删除事件冒泡到行点击事件上
                var display = $('#addMask').css('display');
                var addTimeDisplay = $('#addTimeMask').css('display');
                var isDel = $('.layui-layer-dialog').css('display');
                var isDelTime = localStorage.getItem('delTime');
                if(display === 'block' || isDel === 'block' || addTimeDisplay === 'block' || isDelTime){
                    return;
                }
                //obj.del(); //删除当前行
                //obj.update(fields) //修改当前行数据
                var area = ["90%",echartsHeight];
                layerIndex = layer.open({
                    type: 1
                    , title: '班次时间段' //不显示标题栏
                    // ,class:'full-125'
                    , area: area
                    ,skin:'demo-class'
                    , shade: 0.8
                    , id: 'LAY_layuipro4' //设定一个id，防止重复弹出
                    // ,btn: ['确定', '取消']
                    // ,btnAlign: 'c'
                    , moveType: 1 //拖拽模式，0或者1
                    , content: $('#chart-wrapper')
                    , success: function (layero, index) {
                        form.render();
                        var insertHtml = '<a href="javascript:;" class="layui-btn layui-btn-danger layui-btn-xs time-mid" onclick="timeDel()">删除时间段</a>';
                        $('div.layui-layer-title').after(insertHtml);
                        initEcharts(obj.data);
                    }
                });
            });



            $('.cancel-layer').on('click', function () {
                layer.close(layerIndex);
            })


            form.on('submit(formTest)', function (data) {
                var dataJson = Object.assign({}, data.field);
                var num = $('#confirm').data('num');
                if(num === 0){
                    $.ajax({
                        type: 'POST',
                        data: dataJson,
                        contentType:"application/x-www-form-urlencoded",
                        url: '${bathPath}/numRun/insert.action',
                        success: function (data) {
                            if (data == 'SUCCESS') {
                                layer.close(layerIndex);
                                active.reload();
                            }
                        }
                    })
                }else if(num === 1){
                    dataJson.id  = $('#id').val();
                    $.ajax({
                        type: 'POST',
                        data: dataJson,
                        contentType:"application/x-www-form-urlencoded",
                        url: '${bathPath}/numRun/update.action',
                        success: function (data) {
                            if (data == 'SUCCESS') {
                                layer.close(layerIndex);
                                active.reload();
                            }
                        }
                    })
                }
                return false;
            })

            form.on('submit(formTest2)', function (data) {
                var dataJson = Object.assign({},data.field);
                var sUnits = $('#sUnits').val();
                var sCycle = $('#sCycle').val();
                var sTime = $('#sTime').val();
                dataJson.numRunId = $('#numRunId').val();
                dataJson.schClassId = data.field.classTimeSlot;
                dataJson.endDays = dataJson.startDays = data.field.dateTimeSlot;
                // units 周期单位   1:周 2:天 3:月
                var units = parseInt(sUnits,10);
                var cycle = parseInt(sCycle,10);
                var startTime = sTime + ' 00:00:00';
                var newTime =  GetDateStr(startTime,cycle,units);
                var arr = formatterDayByDay(startTime.split(' ')[0], newTime.split(' ')[0]);
                var startTimeArr = [];

                var startDaysArr = dataJson.dateTimeSlot.split(',');

                for(var i in arr){
                    if(startDaysArr.indexOf(i) > -1){
                        startTimeArr.push(arr[i]);
                    }
                }

                var startDays = startDaysArr.toString();
                dataJson.startDays = startDays;
                dataJson.startTimeStr = startTimeArr.toString();
                dataJson.deilType = 1;
                    $.ajax({
                        type: 'POST',
                        data: dataJson,
                        contentType:"application/x-www-form-urlencoded",
                        url: '${bathPath}/numRunDeil/insert.action',
                        success: function (data) {
                            if (data == 'SUCCESS') {
                                layer.close(layerIndex);
                                active.reload();
                            }
                        }
                    })
                return false;
            })

            var runEvent = function () {
                //初始化表单值
                var title = '';
                if (arguments.length > 0) {
                    var data = arguments[0];
                    $('#confirm').data('num',1);
                    form.val('example', {
                        'id':data.id,
                        'name': data.name,
                        'startTime': formatTime(data.startTime).split(' ')[0],
                        'cycle': data.cycle,
                        'units': data.units
                    })
                    title = '修改班次';
                } else {
                    $('#confirm').data('num',0);
                    form.val('example', {
                        'id':'',
                        'name': '',
                        'startTime': '',
                        'cycle': '',
                        'units': ''
                    })
                    title = '新增班次';
                }
                layerIndex = layer.open({
                    type: 1
                    , title: title //不显示标题栏
                    , area: '350px;'
                    , shade: 0.8
                    , id: 'LAY_layuipro3' //设定一个id，防止重复弹出
                    // ,btn: ['确定', '取消']
                    // ,btnAlign: 'c'
                    , moveType: 1 //拖拽模式，0或者1
                    , content: $('#addMask')
                    , success: function (layero, index) {
                        //日期时间选择器
                        laydate.render({
                            elem: '#startTime'
                            , type: 'date'
                            ,trigger: 'click'
                        });
                        form.render();
                    }
                });
            }
            var runAddTimeEvent = function(data){
                $('#numRunId').val(data.id);
                $('#sTime').val(data.startTime);
                $('#sCycle').val(data.cycle);
                $('#sUnits').val(data.units);
                form.val('example2', {
                    'classTimeSlot': '',
                    'dateTimeSlot': '',
                    'isAddWork': '',
                    'addWorkTime':''
                })
                layerIndex = layer.open({
                    type: 1
                    , title: '添加班次时段' //不显示标题栏
                    , area: '430px;'
                    , shade: 0.8
                    , id: 'LAY_layuipro5' //设定一个id，防止重复弹出
                    // ,btn: ['确定', '取消']
                    // ,btnAlign: 'c'
                    , moveType: 1 //拖拽模式，0或者1
                    , content: $('#addTimeMask')
                    , success: function (layero, index) {
                        initDateTimeSlot(data);
                        formSelects.render('selectId');

                        initGradeTime();

                        form.render();

                    }
                });
                return false;
            }
        });
    }
    // 删除单个时间点
    function timeDel(){
        //要删除的时间段对象
       var timeObjStr = localStorage.getItem('timeDelete');
       if(timeObjStr){
           var timeObj = JSON.parse(timeObjStr);
           $.ajax({
               type: "POST",
               async: false,
               data: timeObj,
               contentType:"application/x-www-form-urlencoded",
               url: '${bathPath}/numRunDeil/deleteOneById.action',
               success: function (data) {
                   if (data == 'SUCCESS') {
                       layer.alert('删除成功!',{
                           icon:1,
                           title:'提示'
                       })
                       var objData = JSON.parse(localStorage.getItem('objData'));
                       initEcharts(objData);
                   }
               }
           })
       }else{
           layer.msg('请选择要删除的时间段',{icon:2});
           return;
       }

    }

    function initEcharts() {
        localStorage.setItem('timeDelete','');
        var colors = ['#2EC7C9'];//两种状态的颜色
        var state = ['时间段'];//两种状态
        var yData = [];
        // var dataJson = [];
        if(arguments[0]){
            var data = arguments[0];
            var cycle = data.cycle;
            var unitsVal = data.units;
            // unit 周期单位   1:周 2:天 3:月

            yData = formatterUnits(data,yData);
            // 获取时间段数据
            $.ajax({
                type: "POST",
                async: false,
                data: {numRunId:data.id,deilType:1},
                contentType:"application/x-www-form-urlencoded",
                url: '${bathPath}/numRunDeil/findNumRunDeilByNumRunId.action',
                success: function (res) {
                    var resData = res.data;
                    var option = null;

                    if(resData.length > 0){

                        var newData = resData.slice(0);

                        if(unitsVal === 1){
                            var unitsDays = 7;
                        }else if(unitsVal === 3){
                            var unitsDays = 30;
                        }
                        // for (var t = 1; t < cycle; t++) {
                        //     if(t === cycle - 1){
                        //        resData  = resData;
                        //     }else{
                        //         for (var k in newData) {
                        //             var days = parseInt(newData[k].sDays, 10) + t * unitsDays;
                        //             resData.push({
                        //                 deilType: newData[k].deilType,
                        //                 schStartTime: newData[k].schStartTime,
                        //                 schEndTime: newData[k].schEndTime,
                        //                 sDays: days
                        //             })
                        //         }
                        //     }
                        // }
                        // 判断是否跨天
                        for(var j in resData){
                            var start = resData[j].schStartTime;
                            var end = resData[j].schEndTime;
                            var startTime = start.split(' ')[1].split(':')[0];
                            var endTime = end.split(' ')[1].split(':')[0];
                            if(startTime > endTime){
                                resData.push({
                                    crossDay:1,
                                    schStartTime:start,
                                    schEndTime: start.split(' ')[0] + ' 24:00:00.0',
                                    sDays:resData[j].sDays
                                })

                                resData.push({
                                    crossDay:1,
                                    schStartTime:start.split(' ')[0] + ' 00:00:00.0',
                                    schEndTime: end,
                                    sDays:parseInt(resData[j].sDays,10) + 1
                                })
                            }
                        }

                        // echart配置
                       var arrData = [];
                       for(var i in resData){
                            if(resData[i].crossDay){
                                arrData.push({
                                    itemStyle: { normal: { color: colors[0] } },
                                    name: '时间段',
                                    value: [resData[i].sDays, formatterTimeStr(resData[i].schStartTime),formatterTimeStr(resData[i].schEndTime),resData[i].crossDay]
                                })
                            }else{
                                arrData.push({
                                    itemStyle: { normal: { color: colors[0] } },
                                    name: '时间段',
                                    value: [resData[i].sDays, formatterTimeStr(resData[i].schStartTime),formatterTimeStr(resData[i].schEndTime)]
                                })
                            }
                       }
                        var yearMonthDay = resData[0].schStartTime.split(' ')[0].replace(/-/ig,'/');
                        var dataJson = [ {
                            itemStyle: { normal: { color: 'rgba(0,0,0,0)' } },//条形颜色
                            name: '时间段',
                            value: ['', yearMonthDay+' 00:00', yearMonthDay + ' 24:00']//0,1,2代表y轴的索引，后两位代表x轴数据开始和结束
                        }];

                        dataJson = dataJson.concat(arrData);
                        option = {
                            color: colors,
                            tooltip: {//提示框
                                formatter: function (params) {
                                    return params.name + ':' + params.value[1].split(' ')[1] + '~' + params.value[2].split(' ')[1];
                                }//数据的值
                            },
                            legend: {//图例
                                data: state,
                                bottom: '1%',
                                selectedMode: false, // 图例设为不可点击
                                textStyle: {
                                    color: '#000'
                                },
                                // show: false
                            },
                            grid: {//绘图网格
                                left: '3%',
                                right: '3%',
                                top: '1%',
                                bottom: '10%',
                                containLabel: true
                            },
                            xAxis: {
                                type: 'time', interval: 3600 * 1000, axisLabel: {
                                    formatter: function (value) {
                                        // var val = '2009/6/1 '+value;
                                        var date = new Date(value);
                                        return getzf(date.getHours());

                                        function getzf(num) {
                                            if (parseInt(num) < 10) {
                                                num = '0' + num;
                                            }
                                            return num;
                                        }
                                    },
                                },
                                position:'top'
                                // data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
                            },
                            yAxis: {
                                data: yData
                            },
                            series: [
                                // 用空bar来显示四个图例
                                {name: state[0], type: 'bar', data: []},
                                // {name: state[1], type: 'bar', data: []},
                                {
                                    type: 'custom', renderItem: function (params, api) {//开发者自定义的图形元素渲染逻辑，是通过书写 renderItem 函数实现的
                                        var categoryIndex = api.value(0);//这里使用 api.value(0) 取出当前 dataItem 中第一个维度的数值。
                                        var start = api.coord([api.value(1), categoryIndex]); // 这里使用 api.coord(...) 将数值在当前坐标系中转换成为屏幕上的点的像素值。
                                        var end = api.coord([api.value(2), categoryIndex]);
                                        var height = 24;//柱体宽度
                                        return {
                                            type: 'rect',// 表示这个图形元素是矩形。还可以是 'circle', 'sector', 'polygon' 等等。
                                            shape: echarts.graphic.clipRectByRect({ // 矩形的位置和大小。
                                                x: start[0],
                                                y: start[1] - height / 2,
                                                width: end[0] - start[0],
                                                height: height
                                            }, { // 当前坐标系的包围盒。
                                                x: params.coordSys.x,
                                                y: params.coordSys.y,
                                                width: params.coordSys.width,
                                                height: params.coordSys.height
                                            }),
                                            style: api.style()
                                        };
                                    },
                                    encode: {
                                        x: [1, 2], // data 中『维度1』和『维度2』对应到 X 轴
                                        y: 0// data 中『维度0』对应到 Y 轴
                                    },
                                    data: dataJson
                                }
                            ]
                        };
                    }else{
                        option = {
                            color: colors,
                            tooltip: {//提示框
                                formatter: function (params) {
                                    return params.name + ':' + params.value[1].split(' ')[1] + '~' + params.value[2].split(' ')[1];
                                }//数据的值
                            },
                            legend: {//图例
                                data: state,
                                bottom: '1%',
                                selectedMode: false, // 图例设为不可点击
                                textStyle: {
                                    color: '#000'
                                },
                                // show: false
                            },
                            grid: {//绘图网格
                                left: '3%',
                                right: '3%',
                                top: '1%',
                                bottom: '10%',
                                containLabel: true
                            },
                            xAxis: {
                                // type: 'time', interval: 3600 * 1000, axisLabel: {
                                //     formatter: function (value) {
                                //         // var val = '2009/6/1 '+value;
                                //         var date = new Date(value);
                                //         return getzf(date.getHours());
                                //
                                //         function getzf(num) {
                                //             if (parseInt(num) < 10) {
                                //                 num = '0' + num;
                                //             }
                                //             return num;
                                //         }
                                //     },
                                // },
                                position:'top',
                                data: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '00']
                            },
                            yAxis: {
                                data: yData
                            },
                            series: [
                                // 用空bar来显示四个图例
                                {name: state[0], type: 'bar', data: []},
                                // {name: state[1], type: 'bar', data: []},
                                {
                                    type: 'custom', renderItem: function (params, api) {//开发者自定义的图形元素渲染逻辑，是通过书写 renderItem 函数实现的
                                        var categoryIndex = api.value(0);//这里使用 api.value(0) 取出当前 dataItem 中第一个维度的数值。
                                        var start = api.coord([api.value(1), categoryIndex]); // 这里使用 api.coord(...) 将数值在当前坐标系中转换成为屏幕上的点的像素值。
                                        var end = api.coord([api.value(2), categoryIndex]);
                                        var height = 24;//柱体宽度
                                        return {
                                            type: 'rect',// 表示这个图形元素是矩形。还可以是 'circle', 'sector', 'polygon' 等等。
                                            shape: echarts.graphic.clipRectByRect({ // 矩形的位置和大小。
                                                x: start[0],
                                                y: start[1] - height / 2,
                                                width: end[0] - start[0],
                                                height: height
                                            }, { // 当前坐标系的包围盒。
                                                x: params.coordSys.x,
                                                y: params.coordSys.y,
                                                width: params.coordSys.width,
                                                height: params.coordSys.height
                                            }),
                                            style: api.style()
                                        };
                                    },
                                    encode: {
                                        x: [1, 2], // data 中『维度1』和『维度2』对应到 X 轴
                                        y: 0// data 中『维度0』对应到 Y 轴
                                    },
                                    data: dataJson
                                }
                            ]
                        };
                    }

                        // $('#chartContent').width(1000);
                        // $('#chartContent').height(600);
                    if(!myChart){
                        myChart = echarts.init(document.getElementById('chartContent'));//加载图形的div
                    }

                    if(yData.length >= 15){
                        var dataZoom = [];
                        var objData = {
                            type: 'slider',
                            show: true,
                            yAxisIndex: [0],
                            left: '0',
                            bottom: '10%',
                            start: 0,
                            end: 50 //初始化滚动条
                        };
                        dataZoom.push(objData);
                        option.dataZoom = dataZoom
                    }
                    //根据窗口的大小变动图表
                    myChart.clear();
                    myChart.setOption(option);//引用
                    //柱状图y轴的长度 option.yAxis.data.length
                    // var autoHeight = option.yAxis.data.length * 30 + 150;
                    // //获取 ECharts 实例容器的 dom 节点。
                    // myChart.getDom().style.height = autoHeight + "px";
                    // myChart.getDom().childNodes[0].style.height = autoHeight + "px";
                    myChart.resize();
                    myChart.off('click');
                    myChart.on('click',function(params){
                        var dd = new Date(data.startTime);
                        if(params.value[3]) {
                            if (params.data.value[1].split(' ')[1] === '00:00') {
                                dd.setDate(dd.getDate() + params.data.value[0] - 1);//获取AddDayCount天后的日期
                            }else{
                                dd.setDate(dd.getDate() + params.data.value[0]);//获取AddDayCount天后的日期
                            }
                        }else{
                            dd.setDate(dd.getDate() + params.data.value[0]);//获取AddDayCount天后的日期
                        }

                        var y = dd.getFullYear();
                        var m = getzf(dd.getMonth()+1);//获取当前月份的日期
                        var d = getzf(dd.getDate());
                        var chartStartTime =  y+"-"+m+"-"+d+" 00:00:00";
                        // 判断是否属于跨天时间段
                        if(params.value[3]){
                            if(params.data.value[1].split(' ')[1] === '00:00'){
                                var jsonObj = {
                                    numRunId:data.id,
                                    startTime:chartStartTime,
                                    sDays:params.data.value[0] - 1
                                }
                            }else{
                                var jsonObj = {
                                    numRunId:data.id,
                                    startTime:chartStartTime,
                                    sDays:params.data.value[0]
                                }
                            }
                        }else{
                            var jsonObj = {
                                numRunId:data.id,
                                startTime:chartStartTime,
                                sDays:params.data.value[0]
                            }
                        }

                        var jsonStr = JSON.stringify(jsonObj);
                        localStorage.setItem('timeDelete',jsonStr);
                    });
                }
            })
        }

    }





    function formatterTimeStr(str){
        str = str.replace(/-/ig, '/');
        var index = str.lastIndexOf(':');
        var newStr = str.slice(0,index);
        return newStr;
    }


    //格式化周期单位值
    function formatterUnits(data,yData){
        var cycle = data.cycle;
        var obj = {};
        var arr = [];
        if(data.units === 1){
            var newArr = ['星期一', '星期二', '星期三', '星期四', '星期五','星期六','星期天'];
            for(var i = 0;i < cycle;i++){
                arr = arr.concat(newArr);
            }
        }else if(data.units === 2){
            if(!arguments[2]){
                var dayCount = cycle+1
            }else{
                var dayCount = cycle;
            }
            for(var i = 0; i < dayCount;i++){
                arr.push('第'+(i+1)+'天');
            }

        }else if(data.units === 3){
            // var newDay = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]
            // for(var i = 0;i < cycle;i++){
            //     arr = arr.concat(newDay);
            // }
            // 获取距离启用日期几个月后的日期
            var startTime = formatTime(data.startTime);
            var newTime =  GetDateStr(startTime,data.cycle,data.units);
            arr = formatterDayByDay(startTime.split(' ')[0], newTime.split(' ')[0]);
        }
        for(var i = 0; i < arr.length; i++){
            obj[i] = arr[i];
        }
        localStorage.setItem('unitsDate',JSON.stringify(obj));
        yData = formatterYData(arr,cycle,yData);
        return yData;
    }


    //获取到对应的周期单位  月:1-31日  周:星期一到星期日 天:周期数*天
    function initDateTimeSlot(data) {
        var yData = [];
        yData = formatterUnits(data,yData,'不多显示一天');
        var html = '';
        var dataJson = null;
        var dataStr = localStorage.getItem('unitsDate');
        if(dataStr){
            dataJson = JSON.parse(dataStr);
            for(var i in dataJson){
                html += '<option value="'+ i + '">'+ dataJson[i]+'</option>'
            }
        }
        $('#dateTimeSlot').html(html);
    }

    function initGradeTime(){
        var html = ' <option value=""></option>';
        $.ajax({
            type: "POST",
            async: false,
            data: "",
            url: '${bathPath}/schClass/findSchClassName.action',
            success: function (data) {
                    for (var i = 0; i < data.length; i++) {
                        var str = formatTime(data[i].startTime).split(" ")[1];
                        var index = str.lastIndexOf(':');
                        var newStr = str.slice(0, index);
                        html += '<option value="' + data[i].id + '">' + data[i].schName + '('+ newStr +')</option>';
                    }
                    $('#classTimeSlot').html(html);
            }
        })
    }

    function formatterYData(arr,cycle,yData){
        // while(cycle >= 1){
            yData = yData.concat(arr);
            // cycle--;
        // }
        return yData;
    }

    //获取多少天后的日期
    function GetDateStr(time,AddDayCount,units) {
        var day = '';
        switch (units) {
            case 1:
                day = 7;
                break;
            case 2:
                day = 1;
                break;
            case 3:
                day = 30;
                break;
        }

        var dd = new Date(time);
        dd.setDate(dd.getDate()+AddDayCount*day - 1);//获取AddDayCount天后的日期
        var y = dd.getFullYear();
        var m = getzf(dd.getMonth()+1);//获取当前月份的日期
        var d = getzf(dd.getDate());
        return y+"-"+m+"-"+d+" 00:00:00";
    }

    //计算开始时间和结束时间相隔天数
    function formatterDayByDay(startTime, endTime) {
        var getDate = function (str) {
            var tempDate = new Date();
            var list = str.split("-");
            tempDate.setFullYear(list[0]);
            tempDate.setMonth(list[1] - 1);
            tempDate.setDate(list[2]);
            return tempDate;
        }
        var date1 = getDate(startTime);
        var date2 = getDate(endTime);
        if (date1 > date2) {
            var tempDate = date1;
            date1 = date2;
            date2 = tempDate;
        }
        date1.setDate(date1.getDate() + 1);
        var dates = [startTime], id = 1;
        while (!(date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth() && date1.getDate() == date2.getDate())) {
            dates[id] = date1.getFullYear() + "-" + getzf(date1.getMonth() + 1) + "-" + getzf(date1.getDate());
            id++;
            date1.setDate(date1.getDate() + 1);
        }
        dates[dates.length] = endTime;
        // 格式化临时排班中的时间
        formatterTemploryYData(dates);
        return dates;
    }


    // 格式化临时排班中的添加时段
    function formatterTemploryYData(dateArr) {
        var obj = {};
        for (var i = 0; i < dateArr.length; i++) {
            obj[i] = dateArr[i];
        }
        localStorage.setItem('unitsDate', JSON.stringify(obj));
    }

    function getzf(num) {
        if (parseInt(num) < 10) {
            num = '0' + num;
        }
        return num;
    }
</script>
</body>
</html>